﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Iacym.Entities;
using Iacym.BusinessLogic;
using Microsoft.Practices.Unity;

namespace Iacym.UI
{
    public partial class FrmMttoCitas : Form
    {
        [Dependency]
        public PersonaBL personaBL { get; set; }

        [Dependency]
        public AgendumBL agendaBL { get; set; }

        //private FrmCitas citasHandler;

        public FrmMttoCitas()
        {
            InitializeComponent();
            this.BuildUp();
        }

        public USUARIO currentUsuarioMttoCitas { get; set; }

        private void FrmMttoCitas_Load(object sender, EventArgs e)
        {
            GenerarHorario();
        }

        public Agendum _currentAgenda
        {
            get { return agendumBindingSource.Current as Agendum; }
            set { agendumBindingSource.DataSource = value; }
        }

        bool isNew = true;

        public void Nuevo()
        {
            isNew = true;
            agendumBindingSource.AddNew();
        }

        public void Editar()
        {
            isNew = false;
            _currentAgenda.PERSONA = personaBL.GetFromPersonaById(_currentAgenda.PersonaId);
            agendumBindingSource.DataSource = _currentAgenda;
            cbHorarioInicio.DataSource = new List<string>() { _currentAgenda.FechaInicio.ToShortTimeString() };
            //cbHorarioInicio.SelectedIndex = -1;
            cbHorarioFin.DataSource = new List<string>() { _currentAgenda.FechaFin.ToShortTimeString() };
            //cbHorarioFin.SelectedIndex = -1;
        }

        List<string> timeIntervals = new List<string>();
        string horaInicio = null;
        string horaFin = null;

        private void GenerarHorario()
        {
            TimeSpan startTime = new TimeSpan(0, 0, 0);
            DateTime startDate = new DateTime(DateTime.MinValue.Ticks); // Date to be used to get shortTime format.
            for (int i = 0; i < 48; i++)
            {
                int minutesToBeAdded = 30 * i;      // Increasing minutes by 30 minutes interval
                TimeSpan timeToBeAdded = new TimeSpan(0, minutesToBeAdded, 0);
                TimeSpan t = startTime.Add(timeToBeAdded);
                DateTime result = startDate + t;
                timeIntervals.Add(result.ToShortTimeString());      // Use Date.ToShortTimeString() method to get the desired format                
            }

            ////Removemos los horarios de receso
            //timeIntervals.RemoveAll(
            //    x => /*x.CompareTo("13:00") == 0 ||*/ x.CompareTo("13:30") == 0
            //      || x.CompareTo("14:00") == 0 || x.CompareTo("14:30") == 0
            //      || x.CompareTo("15:00") == 0 || x.CompareTo("15:30") == 0);
        }

        private void BtnExtPersona_Click(object sender, EventArgs e)
        {
            CargarPersona();
        }

        public void CargarPersona()
        {
            FrmPersona frm = new FrmPersona();
            frm.Extend();
            frm.currentUsuarioPersona = currentUsuarioMttoCitas;
            frm.ShowDialog();
            if (frm.CurrentPersona != null)
            {                
                var agenda = agendumBindingSource.Current as Agendum;

                //var nuevaPersona = personaBL.GetFromPersonaById(frm.CurrentPersona.Id);
                //agenda.PERSONA = nuevaPersona;
                agenda.PERSONA = frm.CurrentPersona;
                //agenda.PersonaId = nuevaPersona.Id;
                agenda.PersonaId = frm.CurrentPersona.Id;
                agendumBindingSource.ResetBindings(true);
            }
        }

        private void cbHorarioInicio_SelectedValueChanged(object sender, EventArgs e)
        {
            horaInicio = cbHorarioInicio.SelectedValue.ToString();
        }

        private void cbHorarioFin_SelectedValueChanged(object sender, EventArgs e)
        {
            horaFin = cbHorarioFin.SelectedValue.ToString();
        }

        private void BtnGuardar_Click(object sender, EventArgs e)
        {
            //Validamos fechas y horario
            //if (TimeSpan.Parse(horaInicio) <= TimeSpan.Parse(horaFin))
            if (Convert.ToDateTime(horaInicio) <= Convert.ToDateTime(horaFin))
            {
                //Codigo para guardar
                var msg = "ERROR";
                Agendum _agenda = agendumBindingSource.Current as Agendum;
                if (_agenda != null)
                {
                    if (isNew)
                    {
                        try
                        {
                            _agenda.FechaInicio = DateTime.Parse(fechaInicioDateTimePicker.Value.Date.ToShortDateString() + " " + horaInicio);
                            _agenda.FechaFin = DateTime.Parse(fechaInicioDateTimePicker.Value.Date.ToShortDateString() + " " + horaFin);
                            _agenda.Motivo = motivoTextBox.Text.ToUpper();
                            agendaBL.AddAgenda(_agenda);
                            MessageBox.Show("Registro Correcto.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            Close();
                        }
                        catch (Exception ex)
                        {
                            msg = ex.Message;
                            MessageBox.Show(msg, "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        try
                        {
                            _agenda.FechaInicio = DateTime.Parse(fechaInicioDateTimePicker.Value.Date.ToShortDateString() + " " + horaInicio);
                            _agenda.FechaFin = DateTime.Parse(fechaInicioDateTimePicker.Value.Date.ToShortDateString() + " " + horaFin);
                            _agenda.Motivo = motivoTextBox.Text.ToUpper();
                            agendaBL.UpdateAgenda(_agenda);
                            MessageBox.Show("Modificación Correcta.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            Close();
                        }
                        catch (Exception ex)
                        {
                            msg = ex.Message;
                            MessageBox.Show(msg, "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
        }

        private void fechaInicioDateTimePicker_ValueChanged(object sender, EventArgs e)
        {
            if (fechaInicioDateTimePicker.Value.Date < DateTime.Now.Date)
            {
                MessageBox.Show("No puede registrar una cita anterior a la fecha actual.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                fechaInicioDateTimePicker.ResetText();
            }
        }

        private void cbHorarioInicio_Click(object sender, EventArgs e)
        {
            cbHorarioInicio.DataSource = new List<string>(timeIntervals);
        }

        private void cbHorarioFin_Click(object sender, EventArgs e)
        {
            cbHorarioFin.DataSource = new List<string>(timeIntervals);
        }
    }
}
